// pages/index/index.tsx
import React, { useState } from 'react'
import {View, Text, ScrollView} from '@tarojs/components'
import './index.scss'
import Taro from "@tarojs/taro";
import AdminService from "@/shared/services/admin/admin.service";
import HeaderTitle from "@/components/HeaderTitle";
import {Avatar, Button, Dialog, InfiniteLoading, Input} from "@nutui/nutui-react-taro";
import {defaultUser, UserModel} from "@/shared/services/model/user";
import {formatBalance} from "@/shared/utils/amountUtil";


const Index: React.FC = () => {

  const [pageNum, setPageNum] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);
  const [searchPhone, setSearchPhone] = useState("");
  const [userList,setUserList] = useState<UserModel[]>([]);
  const [remarkVisible, setRemarkVisible] = useState(false)
  const [optionVisible, setOptionVisible] = useState(false)
  const [currentUser, setCurrentUser] = useState(defaultUser);

  Taro.useLoad(async () => {
    loadUserList(false)
  })

  const loadMore = async () => {
    loadUserList(true)
  }

  const toRecharge = () => {
    setOptionVisible(false)

    Taro.navigateTo({ url: '/pages/admin/save/index?phone=' + currentUser.phone });
  }

  const toCost = () => {
    setOptionVisible(false)

    Taro.navigateTo({ url: '/pages/admin/cost/index?phone=' + currentUser.phone });
  }

  const toEditRemark = () => {
    Taro.navigateTo({ url: `/pages/admin/mark/index?phone=${currentUser.phone}`, events: {
        // 定义要监听的事件
        refreshData: (data) => {
          console.log('收到刷新数据事件', data);
          if(!searchPhone){
            loadUserList(false); // 刷新列表数据
          }else{
            searchUser()
          }
        },},},);
    setRemarkVisible(false)
  }

  const optionDialog = (model: UserModel) => {
    setCurrentUser(model)
    setOptionVisible(true)
  }

  const reMarkDialog = (model: UserModel) => {
    setCurrentUser(model)
    setRemarkVisible(true)
  }

  const loadUserList = async (loadMore: Boolean) => {
    let n = pageNum
    if(loadMore){
      n = pageNum + 1
      setPageNum(n)
      console.log(`setPageNum: ${n}`)

    }else{
      console.log(`setPageNum: 1`)

      setPageNum(1)
    }

    let result = await AdminService.userList({ pageNum: n, pageSize: 100 });

    if(result.code == 0){
      setHasMore(result.data.userList.length > 0)
      setTotal(result.data.total)
      const newList = result.data.userList || [];

      console.log(`userList: ${loadMore} - ${newList.length}`)
      if (loadMore) {
        setUserList((prev) => [...prev, ...newList]);
      } else {
        // ✅ 首次加载或刷新时覆盖
        setUserList(newList);

        if(newList.length < 100){
          setHasMore(false)
        }
      }
    }
  }

  const onPhoneChange = (phone) => {
    if(phone){
      console.log("phone", `搜索具体的手机号${phone}`)
      setSearchPhone(phone)
    }else{
      console.log("phone", `搜索完整数据`)
      setSearchPhone('')
      loadUserList(false)
    }
  }

  const searchUser = async () => {
    if(searchPhone.length < 11){
      Taro.showToast({
        title: '请先输入完整的手机号',
        icon: 'none'
      })
      return
    }

    let result = await AdminService.singleUser({ phone: searchPhone });

    if(result.code == 0){
      setUserList([result.data])
    }else{
      Taro.showToast({
        title: result.msg,
        icon: 'none'
      })
    }
  }

  return (
    <View className="pageContainer">
      <View className='order-header'>
        <HeaderTitle title={'会员列表'} />
      </View>
      <View className={"sec"}>
        <Text className={'total'}>当前用户总数: {total}</Text>
        <View className="search-bar">
          <Input
            type="digit"
            className="search-input"
            placeholder="请输入手机号搜索"
            clearable
            value={searchPhone}
            onChange={(val) => onPhoneChange(val)}
          />
          <Button className="search-btn" type="primary" onClick={searchUser}>
            搜索
          </Button>
        </View>
        <View className="scroll-container">
          <InfiniteLoading
            target="scroll"
            hasMore={hasMore}
            onLoadMore={loadMore}
            loadingText={
              <>
                加载中
              </>
            }
            loadMoreText={
              <>
                没有更多了
              </>
            }
          >
            <View className="user-list">
              {userList.map((item, index) => (
                <View key={index} className="user-item">
                  <Avatar
                    size="large"
                    src={require('@/assets/icon_avatar.png')}
                  />
                  <View className={'userInfo'} onClick={() => reMarkDialog(item)}>
                    <Text className="user-name">{item.realName || item.name || "无名之人"}</Text>
                    <Text className="user-phone">手机号: {item.phone}</Text>
                    <Text className="user-remark">备注: {item.remark || '暂时未设置备注'}</Text>
                  </View>
                  <Text className="user-balance" onClick={() => optionDialog(item)}>{formatBalance(item.balance || "0.00")} ￥</Text>
                </View>
              ))}
            </View>
          </InfiniteLoading>
        </View>

      </View>
      <Dialog
        title={currentUser.realName || currentUser.phone || currentUser.name || "无名之人"}
        visible={remarkVisible}
        confirmText={'修改用户信息'}
        onConfirm={toEditRemark}
        onCancel={() => setRemarkVisible(false)}
      >
        <Text className={'dialog-remark'}>{currentUser.remark || '暂时未设置备注'}</Text>
      </Dialog>

      <Dialog
        title={'用户信息'}
        visible={optionVisible}
        confirmText={'去消费'}
        cancelText={'去充值'}
        onConfirm={toCost}
        onCancel={toRecharge}
        onClose={() => setOptionVisible(false)}
        onOverlayClick={() => setOptionVisible(false)}
      >
        <Text className={'dialog-remark'}>{currentUser.remark || '暂时未设置备注'}</Text>
      </Dialog>
    </View>
  )
}

export default Index
